package com.christophpurrer.shg4;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;

//Need to implement SensorListener
public class ShakeActivity extends Activity implements SensorEventListener {
	// For shake motion detection.
	private SensorManager sensorManager = null;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 800;

	// OnShakeListener that is called when shake is detected
	private OnShakeListener mShakeListener = null;

	/**
	 * interface for shake gesture.
	 */
	public interface OnShakeListener {

		/**
		 * called when shake gesture is detected.
		 */
		void onShake();
	}

	public void setOnShakeListener(OnShakeListener listener) {
		this.mShakeListener = listener;
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// other initialisations
		// start motion detection
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		boolean accelSupported = sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_GAME);

		if (!accelSupported) {
			// on accelerometer on this device
			sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
		}

		final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		this.setOnShakeListener(new OnShakeListener() {
			public void onShake() {
				vibrator.vibrate(100);
				new AlertDialog.Builder(ShakeActivity.this).setPositiveButton(android.R.string.ok, null).setMessage("Shooken!").show();
			}
		});
	}

	protected void onPause() {
		if (sensorManager != null) {
			sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
			sensorManager = null;
		}
		super.onPause();
	}

	@Override
	public void onSensorChanged(SensorEvent sensorEvent) {

		long curTime = System.currentTimeMillis();
		// only allow one update every 100ms.
		if ((curTime - lastUpdate) > 100) {
			long diffTime = (curTime - lastUpdate);
			lastUpdate = curTime;

			// get sensor data
			x = sensorEvent.values[SensorManager.DATA_X];
			y = sensorEvent.values[SensorManager.DATA_Y];
			z = sensorEvent.values[SensorManager.DATA_Z];

			float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
			if (speed > SHAKE_THRESHOLD) {
				mShakeListener.onShake();
			}
			last_x = x;
			last_y = y;
			last_z = z;
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

}